<?php

/* $Id$ */

class q_mysql {

    private static $_instances = array();

    public static function getInstance($setting){
        ksort($setting);
        $key = http_build_query($setting);
        if(empty(self::$_instances[$key])){
            self::$_instances[$key] = new q_mysql($setting);
        }
        return self::$_instances[$key];
    }

    private $link;

    function __construct($setting){
        $this->connect($setting['host'], $setting['user'], $setting['passwd'], $setting['db']);
    }

    public function connect($host, $user, $password, $name){

        $this->link = mysql_connect($host, $user, $password, true);
        if(!$this->link){
            $this->error('Can not connect to MySQL server');
        } 
        $this->query("set names 'utf8'");

        $this->select_db($name);
    }

    public function close() {
        return mysql_close($this->link);
    }


    public function select_db($name) {
        return mysql_select_db($name, $this->link);
    }

    public function query_assoc($sql){
        return $this->fetch($this->query($sql));
    }

    public function query_one($sql){
        return $this->fetch_one($this->query($sql));
    }

    public function query($sql) {

        $result = mysql_unbuffered_query($sql, $this->link);

        if(!$result) {
            $this->error('MySQL Query Error', $sql);
        }

        return $result;
    }

    public function fetch($result){
        return mysql_fetch_assoc($result);
    }

    public function fetch_one($result){
        $array = mysql_fetch_row($result);
        if(isset($array[0])){
            return $array[0];
        } else {
            return false;
        }
    }

    public function affected_rows() {
        return mysql_affected_rows($this->link);
    }

    public function escape($s) {
        return mysql_real_escape_string($s, $this->link);
    }

    public function error($msg, $sql = '') {
        $error = $this->link ? mysql_error($this->link) : mysql_error();

        $log = "q_mysql: " . $msg . "\n " . $error . "\n " . $sql;

        error_log($log);
        echo $log;
        exit;
    }

    public function insert_id() {
        return $this->query_one("SELECT last_insert_id()");
    }

}

